<template>
  <div>
    <el-button
      type="primary"
      icon="el-icon-plus"
      class="topAdd"
      @click="add"
      :disabled="disabled"
      >添加</el-button
    >

    <el-tabs type="border-card" @tab-click="tabsChange">
      <el-tab-pane>
        <span label="全部" slot="label">全部<i class="el-icon-date"></i> </span>
      </el-tab-pane>
      <el-tab-pane>
        <span label="首页" slot="label">首页<i class="el-icon-date"></i> </span>
      </el-tab-pane>
      <el-tab-pane>
        <span label="建材市场" slot="label"
          >建材市场<i class="el-icon-date"></i>
        </span>
      </el-tab-pane>
      <!-- <el-tab-pane>
        <span label="定制" slot="label">定制<i class="el-icon-date"></i> </span>
      </el-tab-pane>
      <el-tab-pane>
        <span label="辅材" slot="label">辅材<i class="el-icon-date"></i> </span>
      </el-tab-pane>
      <el-tab-pane>
        <span label="主材" slot="label">主材<i class="el-icon-date"></i> </span>
      </el-tab-pane> -->

      <el-table
        ref="multipleTable"
        v-loading="loading"
        :data="tableData"
        max-height="550"
        border
        fit
      >
        <el-table-column show-overflow-tooltip prop="id" label="ID" width="90">
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="sort" label="排序">
        </el-table-column>
        <el-table-column show-overflow-tooltip label="图片">
          <template slot-scope="scope">
            <el-image
              style="max-width: 200px"
              :src="imgHeader + scope.row.img"
              :preview-src-list="scope.row.imageList"
              fit="cover"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip label="类型">
          <template slot-scope="scope">
            {{ scope.row.type_text }}
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="nickname"
          label="显示"
          width=""
        >
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.is_show"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-text="显示"
              inactive-text="不显示"
              active-value="1"
              inactive-value="2"
              @change="switchChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip label="操作" width="150">
          <template slot-scope="scope">
            <el-button type="text" @click="bianji(scope.row)">编辑</el-button>
            <el-button type="text" @click="shanchu(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-tabs>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="diaClose"
    >
      <el-form
        :label-position="labelPosition"
        label-width="80px"
        ref="ruleForm"
        :model="fatherObj"
        :rules="rules"
      >
        <el-form-item label="排序" prop="stor">
          <el-input
            v-model="fatherObj.stor"
            class="input"
            placeholder="请输入排序"
          ></el-input>
        </el-form-item>
        <el-form-item label="图片" prop="image">
          <div class="unlodBox">
            <el-upload
              class="upload-demo"
              action
              :http-request="uploadFile"
              ref="upload"
              :limit="fileLimit"
              :on-remove="handleRemove"
              :file-list="fileList"
              :on-exceed="handleExceed"
              :before-upload="beforeUpload"
              :show-file-list="false"
              :headers="headers"
              :on-change="fileChange"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过5M
              </div>
            </el-upload>
            <el-image
              v-if="fatherObj.imagesquan"
              style="width: 50%"
              :src="fatherObj.imagesquan"
              fit="cover"
            ></el-image>
          </div>
        </el-form-item>

        <el-form-item label="是否展示" prop="is_show">
          <el-switch
            v-model="fatherObj.is_show"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-text="显示"
            inactive-text="不显示"
            active-value="1"
            inactive-value="2"
            @change="switchChange2(fatherObj.is_show)"
          >
          </el-switch>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-radio v-model="fatherObj.type" :label="1" :disabled="!disabled2"
            >首页</el-radio
          >
          <el-radio v-model="fatherObj.type" :label="2" :disabled="disabled2"
            >建材市场</el-radio
          >
          <!-- <el-radio v-model="fatherObj.type" :label="3">定制</el-radio>
          <el-radio v-model="fatherObj.type" :label="4">辅材</el-radio>
          <el-radio v-model="fatherObj.type" :label="5">主材</el-radio> -->
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="saveDialog('ruleForm')"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30, 40, 50, 60]"
      :page-size="100"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
  </div>
</template>

<script>
import {
  swiperSet,
  swiperDel,
  swiperAdd,
  swiperList,
  uploadFilec,
  listDate,
} from "../../utils/api";
import { compressImage } from "../../assets/js/compressImage";

export default {
  name: "swiper",
  data() {
    return {
      token: sessionStorage.getItem("token"),
      imgHeader: this.Global.imgHeader,

      dialogTitle: "",
      loading: false,
      tableData: [],
      currentPage: 1,
      limit: 10,
      total: 0,
      dialogVisible: false,
      labelPosition: "right",
      fatherObj: {
        stor: "",
        image: "",
        is_show: "1",
        type: 1,
      },
      srcList2: {},
      disabled: false,
      disabled2: false,
      rules: {
        stor: [{ required: true, message: "请输入排序", trigger: "change" }],
        image: [
          { required: true, message: "请上传商品照片", trigger: "change" },
        ],
        type: [{ required: true, message: "请选择类型", trigger: "change" }],
      },
      fileLimit: 1,
      fileType: ["png", "jpg", "jpeg"],
      fileList: [],
      headers: { "Content-Type": "multipart/form-data" },
      id: -1,
      type: 0,
    };
  },
  methods: {
    tabsChange(tab, event) {
      this.type = tab.index;
      this.swiperList(this.currentPage, this.limit);
    },
    fileChange(file, fileList) {
      this.fileList = fileList;
    },
    // 压缩文件
    compressFile() {
      let config = {
        quality: 0.5, //默认0.5  0-1
        // width:100,
        // height:100
      };
      this.fileList.forEach(async (item) => {
        // console.log("this.fileList1", this.fileList1);
        console.log("原图size1===>", item.size);
        let result = await compressImage({
          file: item.raw,
          config,
          fileName: item.name,
        });
        console.log("压缩后图片size1===>", result.finalFile.size);
        // this.imageList.push(result);
        this.srcList2 = result.finalFile;
        // console.log("aaa", result.finalFile);
        // console.log("bbb", this.srcList2);
        // console.log("this.srcList", this.srcList);
      });
      // console.log("压缩后图片1===>", this.imageList);
    },
    uploadFile(item) {
      this.$message("文件上传中........");
      this.compressFile();
      let timer = setTimeout(() => {
        uploadFilec(this.srcList2).then((res) => {
          if (res.data.status != false || res.data.id != null) {
            res.data.data.saveurl; //半截
            res.data.data.weburl; //全拼
            this.fatherObj.imagesquan = res.data.data.weburl;
            this.fatherObj.image = res.data.data.saveurl;
            this.fileList.push(this.srcList2); //成功过后手动将文件添加到展示列表里
            let i = this.fileList.indexOf(this.srcList2);
            this.handleSuccess();
          }
        });
        clearTimeout(timer);
      }, 1000);
      //上传文件的需要formdata类型;所以要转
      // uploadFilec(item.file).then((res) => {
      //   if (res.data.status != false || res.data.id != null) {
      //     res.data.data.saveurl; //半截
      //     res.data.data.weburl; //全拼
      //     this.fatherObj.imagesquan = res.data.data.weburl;
      //     this.fatherObj.image = res.data.data.saveurl;
      //     this.fileList.push(item.file); //成功过后手动将文件添加到展示列表里
      //     let i = this.fileList.indexOf(item.file);
      //     this.handleSuccess();
      //   }
      // });
    },
    //上传成功后的回调
    handleSuccess() {
      this.$message({
        message: "上传成功",
        type: "success",
      });
      this.handleClose();
    },
    handleRemove() {},
    beforeUpload(file) {
      if (file.type != "" || file.type != null || file.type != undefined) {
        //截取文件的后缀，判断文件类型
        const FileExt = file.name.replace(/.+\./, "").toLowerCase();
        //计算文件的大小
        const isLt5M = file.size / 1024 / 1024 < 1; //这里做文件大小限制
        //如果大于50M
        if (!isLt5M) {
          this.$message.error("上传文件大小不能超过 1MB!");
          return false;
        }
        //如果文件类型不在允许上传的范围内
        if (this.fileType.includes(FileExt)) {
          return true;
        } else {
          this.$message.error("上传文件格式不正确!");
          return false;
        }
      }
    },
    handleClose(i) {
      this.fileList.splice(i, 1); //删除上传的文件
    },
    //超出文件个数的回调
    handleExceed() {
      this.$message({
        type: "warning",
        message: "超出最大上传文件数量的限制！",
      });
      return;
    },
    switchChange(e) {
      this.swiperSet(e.id, e.img, e.is_show, e.sort, e.type);
    },
    switchChange2(e) {
      console.log(e);
    },
    add() {
      this.dialogTitle = "添加轮播图";
      this.fatherObj = {
        stor: "",
        image: "",
        is_show: "1",
        imagesquan: "",
        type: 1,
      };
      if (this.type == 1) {
        this.disabled2 = true;
        this.fatherObj.type = 1;
      } else if (this.type == 2) {
        this.disabled2 = false;
        this.fatherObj.type = 2;
      }
      console.log(this.fatherObj);
      this.dialogVisible = true;
    },
    bianji(row) {
      this.dialogTitle = "编辑轮播图";
      this.fatherObj = {
        stor: row.sort,
        image: row.img,
        is_show: row.is_show,
        imagesquan: this.imgHeader + row.img,
        type: row.type,
      };
      this.id = row.id;
      if (row.is_show != 1) {
        this.dialogVisible = true;
      } else {
        this.dialogVisible = false;
        this.$message.error("显示时不能编辑");
      }

      console.log(this.fatherObj);
    },
    shanchu(row) {
      if (row.is_show == 1) {
        this.$message.error("显示时不能删除");
        return;
      } else {
        this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.swiperDel(row.id);
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
      }
    },
    closeDialog() {
      this.$refs["ruleForm"].resetFields();
      this.dialogVisible = false;
      this.id = -1;
    },
    saveDialog(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log(this.fatherObj);
          if (this.dialogTitle == "编辑轮播图") {
            this.swiperSet(
              this.id,
              this.fatherObj.image,
              this.fatherObj.is_show,
              this.fatherObj.stor,
              this.fatherObj.type
            );
            this.$message({
              message: "编辑成功",
              type: "success",
            });
          } else if (this.dialogTitle == "添加轮播图") {
            console.log(this.fatherObj);
            swiperAdd(
              this.token,
              this.fatherObj.image,
              this.fatherObj.is_show,
              "",
              this.fatherObj.stor,
              this.fatherObj.type
            ).then((res) => {
              console.log(res);
              if (res.data.status) {
                this.$refs["ruleForm"].resetFields();
                this.$message({
                  message: "添加成功",
                  type: "success",
                });
                this.swiperList(this.currentPage, this.limit);
              } else {
                this.$message({
                  message: res.data.msg,
                });
              }
            });
          }

          this.dialogVisible = false;
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    diaClose() {
      this.$refs["ruleForm"].resetFields();
      this.id = -1;
      this.dialogVisible = false;
    },
    // 每页 ${val} 条
    handleSizeChange(val) {
      this.limit = val;
      this.swiperList(this.currentPage, this.limit);
    },
    // 第几页
    handleCurrentChange(val) {
      this.currentPage = val;
      this.swiperList(this.currentPage, this.limit);
    },

    swiperList(page = 1, limit = 10) {
      this.loading = true;
      swiperList(this.token, page, limit, this.type).then((res) => {
        if (res.data.status) {
          this.tableData = res.data.data.data;
          this.tableData.forEach((item) => {
            item.imageList = [this.imgHeader + item.img];
            if (item.type == 1) {
              item.type_text = "首页";
            }
            if (item.type == 2) {
              item.type_text = "建材市场";
            }
            if (item.type == 3) {
              item.type_text = "定制";
            }
            if (item.type == 4) {
              item.type_text = "辅材";
            }
            if (item.type == 5) {
              item.type_text = "主材";
            }
          });
          this.total = res.data.data.count;
          if (this.total >= 10) {
            this.disabled = true;
          } else {
            this.disabled = false;
          }
          let timer = setTimeout(() => {
            this.loading = false;
            clearTimeout(timer);
          }, 400);
        } else {
          this.$message({
            message: res.data.msg,
            type: "error",
            onClose: (res) => {
              this.saveFlag = true;
            },
          });
          if (res.data.msg == "token失效,请重新进行登录") {
            this.$router.push("/login");
          }
          let timer = setTimeout(() => {
            this.loading = false;
            clearTimeout(timer);
          }, 400);
        }
      });
    },
    swiperSet(id, img, is_show, sort, type) {
      swiperSet(this.token, id, img, is_show, "", sort, type).then((res) => {
        if (res.data.status) {
          this.swiperList(this.currentPage, this.limit);
        } else {
          this.$message({
            message: res.data.msg,
            type: "error",
            onClose: (res) => {
              this.saveFlag = true;
            },
          });
          if (res.data.msg == "token失效,请重新进行登录") {
            this.$router.push("/login");
          }
        }
      });
    },
    swiperDel(id) {
      swiperDel(this.token, id).then((res) => {
        if (res.data.status) {
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.swiperList(this.currentPage, this.limit);
        } else {
          this.$message({
            message: res.data.msg,
            type: "error",
            onClose: (res) => {
              this.saveFlag = true;
            },
          });
          if (res.data.msg == "token失效,请重新进行登录") {
            this.$router.push("/login");
          }
        }
      });
    },
  },
  mounted() {
    this.swiperList();

    listDate(this.token, 100, "", 0, 1).then((res) => {});
  },
};
</script>

<style scoped>
/deep/.el-table th.el-table__cell > .cell {
  text-align: center;
}
/deep/.el-table--border .el-table__cell:first-child .cell {
  text-align: center;
}
/deep/.el-table .cell.el-tooltip {
  text-align: center;
}
.topAdd {
  margin: 10px;
}
.el-form-item .input {
  width: 280px;
}
/deep/.upload-demo .el-upload--text {
  border: none;
  width: auto;
  height: auto;
}
/deep/ .el-tabs--border-card > .el-tabs__content {
  padding: 0;
}
.upload-demo {
  line-height: normal;
  margin-bottom: 20px;
}
</style>
